﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class Manage_EditArticle : System.Web.UI.Page
{
    protected List<Annex> annexes;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            #region 加载Templates下面的模版
            string path = Server.MapPath("~/Templates");
            var fs = from aF in (new DirectoryInfo(path)).GetFiles("*.aspx")
                     select new { Name = aF.Name.Replace(".aspx", "") };
            ArticleTemplates.DataSource = fs.ToList();
            ArticleTemplates.DataValueField = "Name";
            ArticleTemplates.DataTextField = "Name";
            ArticleTemplates.DataBind();
            #endregion


            string id = Request.Params["aid"];
            CmsDataContext db = new CmsDataContext();
            var q = from aA in db.Article
                    where aA.ID == id
                    select aA;
            if (q.Count() > 0)
            {
                Article article = q.First();

                ArticleID.Value = article.ID;
                ArticleTitle.Text = article.Title;
                ArticleSubtitle.Text = article.Subtitle;
                ArticleKeywords.Text = article.Keywords;
                ArticleBody.Text = article.Body;
                ArticleFooter.Text = article.Footer;

                if (article.TopicID != null)
                {
                    TopicID.Value = article.TopicID;
                    TopicName.InnerText = article.Topic.Name;
                }

                annexes = article.Annex.ToList();

                ArticleTemplates.SelectedValue = article.Template;
            }
        }
    }

    protected void Save_Click(object sender, EventArgs e)
    {
        CmsDataContext db = new CmsDataContext();
        string id = ArticleID.Value.Trim();
        Article article;
        if (id == "")
        {
            article = new Article();
            article.ID = Toolkit.NextUUID();
            db.Article.InsertOnSubmit(article);
        }
        else
        {
            article = (from aA in db.Article
                       where aA.ID == id
                       select aA).First();
        }

        article.Title = ArticleTitle.Text.Trim();
        article.Subtitle = ArticleSubtitle.Text.Trim();
        article.Keywords = ArticleKeywords.Text.Trim();
        article.TopicID = TopicID.Value.Trim();
        article.Body = ArticleBody.Text.Trim();
        article.Footer = ArticleFooter.Text.Trim();
        article.Published = DateTime.Now;
        article.Clicked = 0;
        article.Url = string.Format("{0}.html", article.ID);
        article.Template = ArticleTemplates.SelectedValue;

        if (article.CreatorID == null)
        {
            article.CreatorID = Convert.ToString(Session["ManagerID"]);
        }

        string aid = AnnexID.Value.Trim();
        if (aid != "")
        {
            string[] ids = aid.Split('|');
            
            #region 将aid中没有的附件删除
            var q = from aA in db.Annex
                     where !ids.Contains(aA.ID) && aA.ArticleID==article.ID
                     select aA;
            db.Annex.DeleteAllOnSubmit(q);
            #endregion

            #region 选出文章的附件
            q = from aA in db.Annex
                where ids.Contains(aA.ID)
                select aA;

            foreach (Annex a in q)
            {
                a.ArticleID = article.ID;
            }
            #endregion
        }

        db.SubmitChanges();

        #region 生成静态文章
        string path = Server.MapPath("~/Html");

        //如果文件夹不存在，则创建
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }

        path = string.Format("{0}/{1}.html", path, article.ID);
        
        //如果文件存在，删除之
        if (File.Exists(path))
        {
            File.Delete(path);
        }

        //获取原文件输入流
        TextWriter tw = new StringWriter();
        Server.Execute(string.Format(@"~/Templates/{0}.aspx?aid={1}", article.Template, article.ID), tw);

        StreamWriter writer = new StreamWriter(path, false, System.Text.Encoding.UTF8);
        writer.Write(tw.ToString());

        writer.Close();
        tw.Close();
        #endregion

        Message.Message = "文章信息保存成功。";
        Message.Location = "./EditArticle.aspx?aid=" + article.ID;
    }
}